import type { Dict } from '@croco/framework/types';

import type { DataFormItemProps, DataFormSchema } from '#/components/data-form/types';
import type { FieldProps, OnActionClickFn, RenderScope } from '#/components/data-table';

import { h, reactive } from 'vue';

import { ElText } from 'element-plus';

export function useTable(enums: Record<string, Array<Dict> | undefined>, onActionClick: OnActionClickFn): FieldProps[] {
    const formatter = (row: any) => {
        const dict = enums.type?.find((item) => item.value === row.type);
        return h(ElText, { type: dict?.listClass || 'info' }, { default: () => dict?.label || '--' });
    };
    return [
        { prop: 'name', label: '名称', search: true, column: { minWidth: 250 } },
        { prop: 'code', label: '键名', search: true, column: { width: 250 } },
        { prop: 'value', label: '键值', column: { width: 300 } },
        { prop: 'type', label: '系统内置', column: { width: 90, align: 'center', formatter } },
        { prop: 'remark', label: '备注', column: { width: 250 } },
        { prop: 'createTime', label: '创建时间', column: { width: 190 } },
        { prop: 'modifyTime', label: '修改时间', column: { width: 190 } },
        {
            column: {
                width: 150,
                render: [
                    { auth: 'system:config:edit', onClick: (scope: RenderScope) => onActionClick({ code: 'edit', scope }) },
                    { auth: 'system:config:remove', onClick: (scope: RenderScope) => onActionClick({ code: 'remove', scope }), type: 'danger' },
                ],
            },
        },
    ];
}

export function useForm(): DataFormSchema {
    const rules = reactive({
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '键名不能为空', trigger: 'blur' }],
    });
    const fields: DataFormItemProps[] = [
        { prop: 'id', primary: true },
        { prop: 'name', label: '名称' },
        { prop: 'code', label: '键名' },
        { prop: 'value', label: '键值' },
        { prop: 'type', label: '系统内置', multiple: false, value: '0' },
        { prop: 'remark', label: '备注' },
    ];
    return { rules, fields };
}
